home *** CD-ROM | disk | FTP | other *** search
Java Source | 2004-04-28 | 2.0 KB | 95 lines |
- import java.util.*;
-
- public class BackgroundJobExecutor implements Runnable {
- private Queue queue;
- private boolean stopRequest = false;
- private boolean stopping = false;
- private Thread thread;
- private final AbstractJob nop = new AbstractJob() {
- public void execute() {
- dispose();
- }
- };
- public BackgroundJobExecutor() {
- queue = new Queue();
- thread = new Thread(this);
- }
- /**
- * Inizia a processare i job
- */
- public void start() {
- thread.start();
- }
- /**
- * Aggiunge un job alla coda
- */
- public boolean add(AbstractJob job) {
- if (job == null) {
- throw new NullPointerException("Job cannot be null");
- }
- if (stopRequest || stopping) {
- throw new IllegalArgumentException("BackgroundJobExecutor has been stopped.");
- }
- return queue.put(job);
- }
- public void run() {
- while (!stopRequest) {
- AbstractJob l = (AbstractJob)queue.get();
- if (l == null) {
- break;
- }
- l.execute();
- }
- dispose();
- }
- /**
- * Termina i job in coda e si ferma
- */
- public void stop() {
- if (stopRequest) {
- throw new IllegalArgumentException("BackgroundJobExecutor has been stopped.");
- }
- if (!stopping) {
- stopping = true;
- queue.putLast(nop);
- }
- }
- /**
- * Ferma l'esecusione senza necessariamente aver terminati i job in coda
- */
- public void dispose() {
- stopRequest = true;
- queue.clear();
- if (thread != null) {
- thread.interrupt();
- thread = null;
- }
- }
- private class Queue {
- private List list = new LinkedList();
- public synchronized Object get() {
- while (list.size() == 0) {
- try {
- wait();
- } catch (InterruptedException ex) {
- return null;
- }
- }
- Object o = list.iterator().next();
- list.remove(o);
- return o;
- }
- public synchronized boolean put(Object obj) {
- boolean b = list.add(obj);
- notify();
- return b;
- }
- public synchronized void clear() {
- list.clear();
- }
- public synchronized void putLast(Object o) {
- list.add(list.size(), o);
- }
- }
- }
-